package network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;


public class TcpConnector implements ITcpConnector{

	private static int BUFFER_SIZE = 2048;
	private static TcpConnector _instance = null;
	
	private Socket socket = null;
	private InputStream input = null;
	private OutputStream output = null;
	
	private boolean CONNECTION = false;
	
	public static TcpConnector instance () {
	
		if(_instance != null)
			return _instance;
		
		_instance = new TcpConnector();
		return _instance;
	}
	
	private TcpConnector(){
		socket = new Socket();
	}

	@Override
	public boolean connect(String host, int port) throws UnknownHostException, IOException {
		// TODO Auto-generated method stub
		if (socket!=null && socket.isConnected()){
			return !CONNECTION;
		}
		
		socket = new Socket(host, port);
		input = socket.getInputStream();
		output = socket.getOutputStream();
		
		CONNECTION = socket.isConnected();
		return CONNECTION;
	}

	@Override
	public boolean disconnect() throws IOException {
		// TODO Auto-generated method stub
		
		input.close();
		output.close();
		socket.close();
		CONNECTION = false;
		
		return !CONNECTION;
	}

	@Override
	public boolean sendMessage(String message) throws IOException {
		// TODO Auto-generated method stub
		
		byte[] str = message.getBytes("ASCII");
		byte[] bytes = new byte[str.length+1];
		int i;
		for (i = 0; i < str.length; i++) {
			byte b = str[i];
			bytes[i] = b;
		}
		bytes[i] = 0x0D ;
		
		output.write(bytes); 
		output.flush();
		
		return false;
	}

	@Override
	public boolean sendMessage(byte[] message) throws IOException {
		// TODO Auto-generated method stub
		output.write(message);
		output.flush();
		
		return true;
	}

	@Override
	public byte[] receiveMessage() throws IOException {
		// TODO Auto-generated method stub
		byte[] message = new byte[BUFFER_SIZE];
		int av = input.available();
		if(av == 0)
			input.read(message);
		
		return message;
	}
	
	
	
}
